import axios from 'axios' //引用axios
import { Toast } from 'vant'
const baseURL = 'http://60.205.253.89/orderApi/'
// axios 配置
//http://192.168.10.20:8080公司接口地址
//http://139.224.133.219:8080线上接口地址
axios.defaults.timeout = 10000
axios.defaults.baseURL = baseURL //这是调用数据接口
axios.defaults.withcRDentials = true //让ajax携带cookie
// http request 拦截器，通过这个，我们就可以把Cookie传到后台
axios.interceptors.request.use(
  config => {
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
// http response 拦截器
axios.interceptors.response.use(
  function(response) {
    //重定向到登录页面
    if (response.data.code === '401') {
      localStorage.clear()
      if (!response.data.url === '') {
        window.location.href = response.data.url //这个url需要后端设置成公用的登录页url
      } else {
        window.location.href = response.data.msg
      }
    }
    return response
  },
  function(error) {
    return Promise.reject(error)
  }
)
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
export default axios
export function request(url, data) {
  return new Promise(async resolve => {
    let responseType = 'json'
    let timeout = 10000
    let headers = { 'Content-Type': 'application/json;charset=UTF-8' }
    let withCredentials = true
    let method = 'post'
    let res = await axios({ baseURL, method, url, data, withCredentials, responseType, timeout, headers })
    if (res.data.code === 200) {
      resolve(res.data)
    } else {
      Toast.fail(res.data.msg)
    }
  })
}
export function axiosAll(list) {
  if (list instanceof Array) {
    return new Promise(resolve => {
      let axiosList = []
      list.map(item => {
        axiosList.push(axios({ baseURL, method: 'post', url: item.url, data: item.data }))
      })
      Promise.all(axiosList).then(res => {
        let isOk = true
        let resList = []
        let msg = ''
        res.map(item => {
          if (item.status != 200) {
            isOk = false
          }
          if (item.data.code != 200) {
            isOk = false
            msg = item.data.msg
          }
          resList.push(item.data)
        })
        if (isOk) {
          resolve(resList)
        } else {
          Toast.fail(msg ? msg : '多接口请求有报错')
        }
      })
    })
  }
}
